package com.appointment.service.impl;

import com.appointment.exception.FrontEndException;
import com.appointment.mapper.AppointmentMapper;
import com.appointment.pojo.Appointment;
import com.appointment.pojo.Log;
import com.appointment.service.AppointmentService;
import com.appointment.service.LogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements AppointmentService {

    @Autowired
    private LogService logService;

    @Override
    @Transactional
    public void updateStatus(String appointmentId, String professorId, int status) {
        if (status != 1 && status != 2) {
            throw new FrontEndException("status值不合法");
        }
        LambdaQueryWrapper<Appointment> appointmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appointmentLambdaQueryWrapper.eq(Appointment::getId, appointmentId);
        appointmentLambdaQueryWrapper.select(Appointment::getId, Appointment::getProfessorId);
        Appointment appointment = getOne(appointmentLambdaQueryWrapper);
        if (appointment == null) {
            throw new FrontEndException("预约记录不存在");
        }
        if (!professorId.equals(appointment.getProfessorId())) {
            throw new FrontEndException("无权操作");
        }
        LambdaQueryWrapper<Log> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
        logLambdaQueryWrapper.eq(Log::getAppointmentId, appointmentId);
        logLambdaQueryWrapper.select(Log::getAuditingStatus);
        logLambdaQueryWrapper.orderByDesc(Log::getCreateTime);
        logLambdaQueryWrapper.last("limit 1");
        Log log = logService.getOne(logLambdaQueryWrapper);
        if (log == null) {
            throw new FrontEndException("审核记录不存在");
        }
        if (log.getAuditingStatus() != 0) {
            throw new FrontEndException("该预约已审核,无法再次审核");
        }
        Log newLog = new Log();
        newLog.setAppointmentId(appointmentId);
        newLog.setAuditingStatus(status);
        logService.save(newLog);
    }

    @Override
    @Transactional
    public void saveWithLog(Appointment appointment) {
        save(appointment);
        Log log = new Log();
        log.setAppointmentId(appointment.getId());
        log.setAuditingStatus(0);
        logService.save(log);
    }

}
